<?php
/**
 * 超链接插件
 *
 * XML配置参数
 * <code>
 * <config>
 *    <columns index="0" href="#" />
 *    <columns index="1" href="#1" />
 * </config>
 * </code>
 *
 * @author mmxie
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Href.php 1021 2011-11-09 01:06:33Z mmxie $
 */
class IG_Data_Plugin_Href extends IG_Data_Plugin
{
    protected $_columnsHref;

    public function setColumnsHref(array $columnsHref)
    {
        if (!is_array(current($columnsHref))) {
            $columnsHref = array($columnsHref);
        }

        foreach ($columnsHref as $item) {
            $this->_columnsHref[$item['index']] = $item['href'];
        }
    }

    public function getColumnsHref()
    {
        return $this->_columnsHref;
    }

    public function after()
    {
        $body = $this->getSource()->getBody();
        if (!isset($body['body']['table']['rows'])) {
            return ;
        }

        $search = array();
        $columnCount = count(current($body['body']['table']['rows']));
        for ($i = 0; $i < $columnCount; $i++) {
            $search[] = '{' . $i . '}';
        }

        $params = $this->getSource()->getParams();
        foreach (array_keys($params) as $key) {
            $search[] = '{' . $key . '}';
        }

        foreach ($body['body']['table']['rows'] as &$row) {
            foreach ($this->getColumnsHref() as $index => $href) {
                $row[$index] = '<a target="_newTab" href="'
                             . str_replace($search, array_merge($row, $params), $href) . '">'
                             . $this->getView()->escape($row[$index])
                             . '</a>';
            }
        }
        $this->getSource()->setBody($body);
    }

    public function afterXmlHttpRequest()
    {
        $this->after();
    }
}